import pandas as pd
import requests
import json
import time
from typing import Dict, Any, List
from dotenv import load_dotenv
import os
import re

# 加载环境变量
load_dotenv()


def read_excel_file(file_path: str) -> pd.DataFrame:
    """读取Excel文件中的产品名称"""
    try:
        df = pd.read_excel(file_path)
        print(f"成功读取Excel文件，共 {len(df)} 行数据")
        return df
    except Exception as e:
        print(f"读取Excel文件时出错: {e}")
        raise


def call_dify_api(product_name: str) -> Dict[str, Any]:
    """调用Dify的chatflow API进行产品分类"""
    # 从环境变量获取配置
    api_url = os.getenv("DIFY_API_URL")
    api_token = os.getenv("DIFY_API_TOKEN")
    user_id = os.getenv("USER_ID", "user123")
    timeout = int(os.getenv("REQUEST_TIMEOUT", "30"))

    if not api_url or not api_token:
        raise ValueError(
            "API配置不完整：请检查.DOTENV文件中的DIFY_API_URL和DIFY_API_TOKEN"
        )

    headers = {
        "Authorization": f"Bearer {api_token}",
        "Content-Type": "application/json",
    }

    # 根据curl示例构造请求体
    payload = {
        "inputs": {},
        "query": product_name,
        "response_mode": "blocking",
        "user": user_id,
        "conversation_id": "",  # 添加必需的字段
    }

    print(f"发送请求到 {api_url}")
    print(f"请求体: {payload}")

    try:
        response = requests.post(
            api_url, headers=headers, json=payload, timeout=timeout
        )
        response.raise_for_status()

        result = response.json()
        print(f"API调用成功: {product_name}")
        print(f"响应结果: {result}")

        data_dic = json.loads(
            re.sub(r"```json\s*|\s*```", "", result.get("answer", "").strip())
        )

        return data_dic

    except Exception as e:
        print(f"调用API时出错 {product_name}: {e}")
        print(
            f"响应状态码: {response.status_code if 'response' in locals() else 'N/A'}"
        )
        print(f"响应内容: {response.text if 'response' in locals() else 'N/A'}")
        return {"error": str(e)}


def parse_api_result(result: Dict[str, Any], product_name: str) -> Dict[str, str]:
    """解析API返回的结果"""
    try:
        parsed_result = {}

        # 根据API返回的实际格式进行解析
        if isinstance(result, dict):
            print(f"解析结果为字典： {result}")

            # 优先从data字段中提取信息
            parsed_result["品名"] = product_name
            parsed_result["功能类别"] = result.get("功能类别", "未识别")
            parsed_result["行业类别"] = result.get("行业类别", "未识别")

        elif isinstance(result, list) and len(result) > 0:
            print(f"解析结果为列表： {result}")
            first_entry = result[0]
            parsed_result["品名"] = product_name
            parsed_result["功能类别"] = first_entry.get("功能类别", "未识别")
            parsed_result["行业类别"] = first_entry.get("行业类别", "未识别")

        else:
            # 如果无法解析，使用默认值
            parsed_result["品名"] = product_name
            parsed_result["功能类别"] = "解析失败"
            parsed_result["行业类别"] = "解析失败"

        print(f"解析结果: {parsed_result}")

        return parsed_result
    except Exception as e:
        print(f"解析API结果时出错: {e}")
        return {"品名": product_name, "功能类别": "解析失败", "行业类别": "解析失败"}


def save_results_to_excel(results: List[Dict[str, str]], output_file: str):
    """将结果保存到Excel文件"""
    try:
        df = pd.DataFrame(results)
        df.to_excel(output_file, index=False)
        print(f"结果已保存到 {output_file}")
    except Exception as e:
        print(f"保存Excel文件时出错: {e}")


def main():
    # 开始计时
    start_time = time.perf_counter()

    # 从环境变量获取配置
    input_file = os.getenv("INPUT_FILE", "品名测试 - 少.xlsx")
    output_file = os.getenv("OUTPUT_FILE", "产品分类结果.xlsx")
    delay = int(os.getenv("DELAY_BETWEEN_REQUESTS", "1"))

    print("开始处理产品名称分类...")
    print(f"输入文件: {input_file}")
    print(f"输出文件: {output_file}")

    # 1. 读取Excel文件
    df = read_excel_file(input_file)

    # 2. 获取产品名称列（假设列名为"产品名"）
    if "产品名" not in df.columns:
        print("警告：未找到'产品名'列，请检查Excel文件格式")
        # 尝试使用第一列作为产品名
        product_column = df.columns[0]
        print(f"使用第一列 '{product_column}' 作为产品名列")
    else:
        product_column = "产品名"

    # 3. 处理每个产品名称
    results = []
    total_products = len(df)

    for index, row in df.iterrows():
        product_name = str(row[product_column])
        print(f"[{index+1}/{total_products}] 正在处理: {product_name}")

        # 调用API
        api_result = call_dify_api(product_name)

        # 解析结果
        parsed_result = parse_api_result(api_result, product_name)
        results.append(parsed_result)

        # 添加延迟以避免API限制
        time.sleep(delay)

    # 4. 保存结果
    save_results_to_excel(results, output_file)

    # 结束计时并计算耗时
    end_time = time.perf_counter()
    total_time = end_time - start_time

    print("处理完成！")
    print(f"总共处理了 {len(results)} 个产品")
    print(f"总耗时: {total_time:.2f} 秒")
    if len(results) > 0:
        print(f"平均每个产品耗时: {total_time/len(results):.2f} 秒")


if __name__ == "__main__":
    main()
